<script lang="ts" setup>
import {ref} from "vue";
import {useRoute, useRouter} from "vue-router";
import {ElMessage} from "element-plus";
import type {PostAction} from "../../network/api/PostApi.ts";
import PostForm from "../../components/post/PostForm.vue";
import type {NgaLocation} from "../../network/types/NgaLocation.ts";
import {ReplyListRoute} from "../index.ts";
import {toNumber} from "../../utils/Utils.ts";

const route = useRoute();
const router = useRouter();

// 只能为： new|modify|reply|quote
const action = ref<PostAction>('new')
const fid = ref<number>()
const stid = ref<number>()
const tid = ref<number>()
const pid = ref<number>()
const comment = ref<1>()

action.value = route.params.action as PostAction
fid.value = toNumber(route.query.fid)
stid.value = toNumber(route.query.stid)
tid.value = toNumber(route.query.tid)
pid.value = toNumber(route.query.pid)
comment.value = route.query.comment ? 1 : undefined

const goBack = () => window.history.back()

// 检查参数
switch (action.value) {
  case 'new':
    if (!fid.value && !stid.value) {
      ElMessage.error("缺少必须参数: fid 或 stid")
      goBack()
    }
    break;
  case 'modify':
    if (!tid.value) {
      ElMessage.error("缺少必须参数: tid")
      goBack()
    }
    break;
  case 'quote':
  case 'reply':
    if (!tid.value && !pid.value) {
      ElMessage.error("缺少必须参数: tid 或 pid")
      goBack()
    }
    break;
  default:
    ElMessage.error("不合法的type: " + action.value)
    goBack()
    break;
}

const onError = (error: any) => {
  console.error('onError', error)
  if (error?.hasOwnProperty('code')) {
    const {code, message} = error
    if (code === 23) {
      goBack()
    } else {
      ElMessage.error(`${code}: ${message}`)
    }
  }
}

const onSuccess = (location: NgaLocation) => {
  switch (action.value) {
    case "new": {
      router.push({name: ReplyListRoute.LIST, params: {tid: location.tid}})
      console.log('跳转到新帖', location)
      break
    }
    case "modify": {
      console.log('跳转到被编辑楼层', location)
      if (location.pid) {
        router.push({name: ReplyListRoute.SINGLE, params: {pid: location.pid}, query: {to: '1'}})
      } else {
        router.push({name: ReplyListRoute.LIST, params: {tid: location.tid}})
      }
      break
    }
    default: {
      router.push({name: ReplyListRoute.LIST, params: {tid: location.tid}, query: {page: 'e'}, hash: '#P' + location.pid})
      console.log('跳转到最新页', location)
    }
  }
}

</script>

<template>
  <!--正文编辑框-->
  <div>
    <post-form
        :action="action"
        :comment="comment"
        :fid="fid"
        :pid="pid"
        :stid="stid"
        :tid="tid"
        @error="onError"
        @success="onSuccess"
    />
  </div>
</template>

<style scoped>

</style>